//
//  YWUnfinishInspectionMissionCell.m
//  maintain
//
//  Created by Kyo on 16/9/29.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWUnfinishInspectionMissionCell.h"
#import "UIColor+CustomColors.h"
#import "UIImageView+WebCache.h"
#import "Masonry.h"
//#import "UILabel+AttributedText.h"
#import "NSDate+Additions.h"
#import "YWMacro.h"
#import "YWCommonTool.h"
#import "YYLabel.h"

#import "YWInspectionMissionModel.h"
#import "YWHandler.h"
#import "YWInspectionMissionManager.h"
#import "YWEquipment.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWAnimationView.h"
#import "YWKeepWatchMissionManager.h"

#import "YWContactManager.h"
#import "YWReplyManager.h"
#import "YWReply.h"

@interface YWUnfinishInspectionMissionCell()
/** 设备|位置巡查 */
@property (nonatomic, strong) YYLabel *inspectionType;
/** 头像 */
@property (nonatomic, strong) UIImageView *headImageView;
/** 发布者 */
@property (nonatomic, strong) YYLabel *responseName;
/** 发布时间 */
@property (nonatomic, strong) YYLabel *createTime;
/** 编号 */
@property (nonatomic, strong) YYLabel *numberLabel;
/** 巡查人 */
@property (nonatomic, strong) YYLabel *inspectionManLabel;
/** 巡查地点 */
@property (nonatomic, strong) YYLabel *inspectionSiteLabel;
////巡查路线:
//@property (nonatomic, strong) UILabel *inspectionRoutL;
//巡查时间
@property (nonatomic, strong) YYLabel *inspectionTimeSoltLabel;
//填写的总数
@property (nonatomic, strong) YYLabel *totalequipmentLabel;
//填写本次已完成个数
@property (nonatomic, strong) YYLabel *completedTimesLable;
@end

@implementation YWUnfinishInspectionMissionCell

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    YWUnfinishInspectionMissionCell *cell = [tableView dequeueReusableCellWithIdentifier:YWUnfinishInspectionMissionCellIdentifier];
    if (cell == nil) {
        cell = [[YWUnfinishInspectionMissionCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:YWUnfinishInspectionMissionCellIdentifier];
    }
    return cell;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.layer.shouldRasterize = YES;
        self.layer.rasterizationScale = [UIScreen mainScreen].scale;
        [self setUpSubviews];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        //self.separatorInset = UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, 0);
    }
    return self;
}

- (void)setMissionModel:(YWInspectionMissionModel *)missionModel{
    _missionModel = missionModel;
    
    //头像
    NSString* downloadUrl = [YWCommonTool pictureDownloadUrl:_missionModel.creator.headIcon];
    [_headImageView sd_setImageWithURL:[NSURL URLWithString:downloadUrl] placeholderImage:[UIImage imageNamed:@"profile_headimage"]];
    _responseName.text = _missionModel.creator.userName;
    //时间
    _createTime.text = [YWCommonTool showTimeWithNormalFormatter:_missionModel.createTime/1000];
    //编号
    NSString *sequenceText = _missionModel.missionSequence.length>0?_missionModel.missionSequence:NSLocalizedString(@"none", nil);
    _numberLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"codeFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:sequenceText secondColor:[UIColor customYellowColor] font:kContentFont];
    
    //巡查人
    NSString *handlerText = [YWCommonTool handlerNamesWithHandlers:_missionModel.executors];
    _inspectionManLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"inspectionExecutorFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:handlerText secondColor:[UIColor customYellowColor] font:kContentFont];
    
    //巡查 设备|位置类型
    _inspectionType.text = _missionModel.inspectionLine.lineType==YWInspectionLineTypeEquipment?NSLocalizedString(@"equipmentInspection", nil):NSLocalizedString(@"locationInspection", nil);
    
    //位置
    YWBuilding *building = nil;
    if (_missionModel.buildingId.length) {
        building = [[YWBuildingManager shareManager] buildingWithId:_missionModel.buildingId];
    }else{
        if (_missionModel.inspectionLine.lineType == YWInspectionLineTypeEquipment) {
            YWEquipment *equipment = _missionModel.inspectionLine.equipments.count?_missionModel.inspectionLine.equipments[0]:nil;
            if (equipment.buildingId) {
                building = [[YWBuildingManager shareManager] buildingWithId:equipment.buildingId];
            }else{
                building = [[YWBuildingManager shareManager] buildingWithEquipmentId:equipment.equipmentId];
            }
        }else{
            YWInspectionLineLocationRel *locationRel = _missionModel.inspectionLine.locationRels.count>0?_missionModel.inspectionLine.locationRels[0]:nil;
            building = [[YWBuildingManager shareManager] buildingWithLocationId:locationRel.locationId];
        }
    }
    
    //位置
    NSString *locationText = building.buildingName.length>0?building.buildingName:NSLocalizedString(@"none", nil);
    _inspectionSiteLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"locationFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:locationText secondColor:[UIColor blackColor] font:kContentFont];
    
    //    本次已完成
    NSArray *intervalArray = missionModel.currentLooperTimeArray;//[YWCommonTool looperTimeArrayWithMission:missionModel];
    
    NSTimeInterval lineRecordStarTime = (intervalArray?[[intervalArray firstObject] longLongValue]:0);
    NSString *uniqueTag = missionModel.uniqueTag;//[YWCommonTool uniqueTagWithMission:missionModel];
    NSInteger count = [[YWInspectionMissionManager shareManager] countOfInspectionEquipmentRecordWithUniqueTag:uniqueTag];
    
    NSString *finishText = [NSString stringWithFormat:@"%ld个",(long)count];
    _completedTimesLable.attributedText = [YWCommonTool attributedTextWithFirstText:@"本次已完成: " firstColor:[UIColor customTextGrayBlackColor] secondText:finishText secondColor:[UIColor customYellowColor] font:kContentFont];
    
    //    巡查时间
    NSTimeInterval lineRecordEndTime = (intervalArray?[[intervalArray lastObject] longLongValue]:0);
    NSString *startTime = nil;
    NSString *endTime = nil;
    if (missionModel.inspectionLine.intervalMinute>24*60) {
        startTime = [YWCommonTool showTime:lineRecordStarTime andFormatter:KTimeFormatShortDate];
        endTime = [YWCommonTool showTime:lineRecordEndTime andFormatter:KTimeFormatShortDate];
    }else{
        startTime = [YWCommonTool showTime:lineRecordStarTime andFormatter:KTimeFormatShortTime];
        endTime = [YWCommonTool showTime:lineRecordEndTime andFormatter:KTimeFormatShortTime];
    }
    NSString *timeString = (lineRecordStarTime==0 && lineRecordEndTime==0) ? NSLocalizedString(@"notWorkTime", nil) :[NSString stringWithFormat:@"%@-%@",startTime,endTime];
    //[_inspectionTimeSoltLabel labelText:@"巡查时间: " withAttributedText:timeString andAttributedColor:[UIColor customYellowColor]];
    _inspectionTimeSoltLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"inspectionTime", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:timeString secondColor:[UIColor customYellowColor] font:kContentFont];
    
    if ([YWCommonTool containSelfInHandlers:_missionModel.executors]) {
        if (_missionModel.inspectionLine.lineType ==YWInspectionLineTypeEquipment) {
            //[_totalequipmentLabel labelText: @"巡查设备总数: " withAttributedText:[NSString stringWithFormat:@"%lu个", (unsigned long)_missionModel.inspectionLine.equipments.count] andAttributedColor:[UIColor customYellowColor]];
            NSString *equCountText = [NSString stringWithFormat:@"%lu个", (unsigned long)_missionModel.inspectionLine.equipments.count];
            _totalequipmentLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"inspectionEquipmentCount", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:equCountText secondColor:[UIColor customYellowColor] font:kContentFont];
        }else{
            //[_totalequipmentLabel labelText:@"巡查位置总数: " withAttributedText:[NSString stringWithFormat:@"%lu个", (unsigned long)_missionModel.inspectionLine.locationRels.count] andAttributedColor:[UIColor customYellowColor]];
            NSString *locationCountText = [NSString stringWithFormat:@"%lu个", (unsigned long)_missionModel.inspectionLine.locationRels.count];
            _totalequipmentLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"inspectionLocationCount", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:locationCountText secondColor:[UIColor customYellowColor] font:kContentFont];
        }
    }else{
        _totalequipmentLabel.text = @"";
        _completedTimesLable.text = @"";
    }
    //任务参与人，要把报障人算进去
    NSMutableArray *tempArray = [NSMutableArray array];
    NSMutableArray *observerArray = [NSMutableArray array];
    [tempArray addObject:_missionModel.creator];
    [tempArray addObjectsFromArray:_missionModel.executors];
    [tempArray addObjectsFromArray:_missionModel.observers];
    for (YWHandler *handler in tempArray) {
        NSInteger uniqueId = handler.uniqueId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
        NSArray *array = [[observerArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==0) {
            [observerArray addObject:handler];
        }
    }
    NSString * firstStr = [NSString stringWithFormat:@"参与人(%ld): ",(long)observerArray.count];
    NSMutableString *observerName = [[NSMutableString alloc] init];
    [observerArray enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        if (observerName.length && idx!=0) {
            [observerName appendString:@" "];
        }
        [observerName appendString:handler.userName];
    }];
    
    NSString * nameStr = [NSString stringWithFormat:@"%@",observerName?:@""];//参与者要加进来
    
    self.observersLabel.attributedText = [YWCommonTool attributedTextWithFirstText:firstStr firstColor:[UIColor customTextGrayBlackColor] secondText:nameStr secondColor:[UIColor customBlueColor] font:kContentFont];
    //有评论
    NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:_missionModel.inspectionMissionId andRelationType:YWReplyRelationTypeInspection];
    if (commentArray.count>0) {
        YWReply * reply = [commentArray firstObject];
        NSString * replyCount = [NSString stringWithFormat:@"评论(%ld): ",commentArray.count];
        //    时间
        NSString * timeStr = [YWCommonTool recordDateByFormatTimeString:reply.replyTime/1000 showYear:YES];
        NSString * timeText = [NSString stringWithFormat:@"  %@",timeStr];
        //    内容
        NSString *replyName = [NSString stringWithFormat:@"%@: ",reply.replier.userName];
        NSString *atUserName = reply.atUser.userName.length>0?[NSString stringWithFormat:@" @%@",reply.atUser.userName]:@"";
        NSString * content = atUserName.length?[NSString stringWithFormat:@" %@  ",reply.content.length>0?reply.content:@""] : (reply.content.length>0?reply.content:@"");
        
        self.replyLabel.attributedText = [YWCommonTool attributedTextWithFirstText:replyCount firstColor:[UIColor customTextGrayColor] firstFont:kContentFont secondText:replyName secondColor:[UIColor customBlueColor] secFont:kContentFont thirdText:atUserName thirdColor:[UIColor customBlueColor] thirdFont:kContentFont fourthText:content fourthColor:[UIColor blackColor] fourFont:kContentFont fifthText:timeText fifthColor:[UIColor customTextGrayColor] fifthFont:[UIFont systemFontOfSize:13]];
    }else{
        self.replyLabel.attributedText = nil;
    }
    
    self.inspectionManLabel.preferredMaxLayoutWidth = self.inspectionManLabel.frame.size.width;
    self.inspectionSiteLabel.preferredMaxLayoutWidth = self.inspectionSiteLabel.frame.size.width;
    self.inspectionTimeSoltLabel.preferredMaxLayoutWidth = self.inspectionTimeSoltLabel.frame.size.width;
    self.observersLabel.preferredMaxLayoutWidth = self.observersLabel.frame.size.width;
    self.replyLabel.preferredMaxLayoutWidth = self.replyLabel.frame.size.width;
}

- (void)setUpSubviews{
    UIView *superview = self.contentView;
    
    [self.headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.mas_equalTo(superview).offset(8);
        make.width.and.height.mas_equalTo(@46);
    }];
    
    [self.responseName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(_headImageView.mas_centerY).offset(-2);
        make.left.mas_equalTo(_headImageView.mas_right).offset(6);
    }];
    
    [self.createTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_responseName);
        make.top.mas_equalTo(_responseName.mas_bottom).offset(4);
    }];
    
    [self.inspectionType mas_makeConstraints:^(MASConstraintMaker *make) {
        make.baseline.mas_equalTo(_responseName);
        make.right.mas_equalTo(superview).offset(-8);
    }];
    
    [self.numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_headImageView.mas_bottom).offset(6);
        make.left.mas_equalTo(superview).offset(8);
        make.right.mas_equalTo(superview).offset(-8);
    }];
    
    [self.inspectionManLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_numberLabel.mas_bottom).offset(6);
    }];
    
    [self.inspectionSiteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_inspectionManLabel.mas_bottom).offset(6);
        
    }];
    
    [self.inspectionTimeSoltLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_inspectionSiteLabel.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(@[_numberLabel, _inspectionManLabel, _inspectionSiteLabel]);
    }];
    /**
     *  巡查点总数   已完成
     */
    [self.totalequipmentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_inspectionTimeSoltLabel.mas_bottom).offset(6);
        make.left.mas_equalTo(_numberLabel);
        make.right.mas_equalTo(superview.mas_centerX);
//        make.bottom.mas_equalTo(superview).offset(-6);
    }];
    [self.completedTimesLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.baseline.mas_equalTo(_totalequipmentLabel);
        make.left.mas_equalTo(superview.mas_centerX);
    }];
    
    [self.separatorLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_totalequipmentLabel.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(superview);
        make.height.mas_equalTo(@1.0);
    }];
    
    [self.observersLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.separatorLineView.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(_numberLabel);
    }];
    [self.replyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.observersLabel.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(_numberLabel);
        make.bottom.mas_equalTo(superview).offset(-6);
    }];
}

//- (void)layoutSubviews{
//    [super layoutSubviews];
//    
//}

- (UIImageView *)headImageView{
    if (!_headImageView) {
        UIImageView *imageView = [UIImageView new];
        imageView.clipsToBounds = YES;
        imageView.layer.cornerRadius = 46/2;
        _headImageView = imageView;
        [self.contentView addSubview:_headImageView];
    }
    return _headImageView;
}

- (YYLabel *)responseName{
    if (!_responseName) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor blackColor];
        _responseName = label;
        [self.contentView addSubview:_responseName];
    }
    return _responseName;
}

- (YYLabel *)createTime{
    if (!_createTime) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _createTime = label;
        [self.contentView addSubview:_createTime];
    }
    return _createTime;
}

- (YYLabel *)inspectionType{
    if (!_inspectionType) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _inspectionType = label;
        [self.contentView addSubview:_inspectionType];
    }
    return _inspectionType;
}

- (YYLabel *)numberLabel{
    if (!_numberLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _numberLabel = label;
        [self.contentView addSubview:_numberLabel];
    }
    return _numberLabel;
}

- (YYLabel *)inspectionManLabel{
    if (!_inspectionManLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.numberOfLines = 0;
        label.textColor = [UIColor customTextGrayBlackColor];
        _inspectionManLabel = label;
        [self.contentView addSubview:_inspectionManLabel];
    }
    return _inspectionManLabel;
}

- (YYLabel *)inspectionSiteLabel{
    if (!_inspectionSiteLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.numberOfLines = 0;
        label.textColor = [UIColor customTextGrayBlackColor];
        _inspectionSiteLabel = label;
        [self.contentView addSubview:_inspectionSiteLabel];
    }
    return _inspectionSiteLabel;
}

//- (UILabel *)inspectionRoutL{
//    if (!_inspectionRoutL) {
//        UILabel *label = [[UILabel alloc] init];
//        label.font = kContentFont;
//        label.numberOfLines = 0;
//        label.textColor = [UIColor customTextGrayBlackColor];
//        _inspectionRoutL = label;
//        [self.contentView addSubview:_inspectionRoutL];
//    }
//    return _inspectionRoutL;
//}

- (YYLabel *)inspectionTimeSoltLabel{
    if (!_inspectionTimeSoltLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.numberOfLines = 0;
        label.textColor = [UIColor customTextGrayBlackColor];
        _inspectionTimeSoltLabel = label;
        [self.contentView addSubview:_inspectionTimeSoltLabel];
    }
    return _inspectionTimeSoltLabel;
}

- (YYLabel *)totalequipmentLabel{
    if (!_totalequipmentLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _totalequipmentLabel = label;
        [self.contentView addSubview:_totalequipmentLabel];
    }
    return _totalequipmentLabel;
}

- (YYLabel *)completedTimesLable{
    if (!_completedTimesLable) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _completedTimesLable = label;
        [self.contentView addSubview:_completedTimesLable];
    }
    return _completedTimesLable;
}

@end
